package com.nuc6.controller;

import com.nuc6.entity.User;
import com.nuc6.mapper.UserMapper;
import com.nuc6.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author zwp
 * @version 1.0
 */
@Controller
public class LoginController {
    @Resource
    private UserMapper userMapper;
    @GetMapping("/login")
    public String toLogin(){
        return "login";
    }
    @PostMapping("/login")
    public String login(HttpServletRequest request,
                        Model model,
                        HttpSession session){

        //取出前端传入的信息
        String tel = request.getParameter("tel");
        String password = request.getParameter("password");

        //从数据库取出保存好的信息，与传入的信息做判断
        if(tel.equals(userMapper.getTel(tel)) && password.
                equals(userMapper.getPassword(tel))){
            if(2 == userMapper.getIdentity(tel)){
                session.setAttribute("pwd",password);
                session.setAttribute("tel",tel);
                return "redirect:http://localhost:8080";
            }
            if(1 == userMapper.getIdentity(tel)){
                session.setAttribute("pwd",password);
                session.setAttribute("tel",tel);
                return "redirect:/hr";
            }
            session.setAttribute("tel",tel);
            session.setAttribute("pwd",password);
            return "redirect:/interviewer";
        }else{
            //不合法，就重新登录
            model.addAttribute("msg", "账号/密码错误");
            return "login";
        }
    }
    @GetMapping("/register")
    public String toRegister(){
        return "register";
    }
    @PostMapping("/register")
    public String register(HttpServletRequest request,
                           Model model){
        String tel = request.getParameter("tel");
        String password = request.getParameter("password");
        User user = new User(tel, password);
        int result = userMapper.addUser(user);
        if(result != 0){
            model.addAttribute("msg", "注册成功，请登录");
            return "login";
        }
        model.addAttribute("msg", "注册失败");
        return "login";
    }
}
